<template>
  <div class="card" id="flight-refund-order-new">
    <div class="card-header">
      <h5 class="text-primary">新建退票单</h5>
    </div>

    <table class="table table-sm table-striped mb-0">
      <thead>
        <tr>
          <th>票号</th>
          <th>姓名</th>
          <th class="d-none d-sm-table-cell">证件号</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(psg, index) of psgList" :key="index">
          <td>
            {{ psg.ticketNo }}
          </td>
          <td>{{ psg.name }}</td>
          <td class="d-none d-sm-table-cell">{{ psg.idNo }}</td>
          <td><input type="checkbox" v-model="psg.selected" /></td>
        </tr>
      </tbody>
    </table>
    <table class="table table-sm table-striped mb-0">
      <thead>
        <tr class="">
          <th>销售价</th>
          <th>税</th>
          <th>成本</th>
          <th>实收</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="text-center">
            <input
              type="text"
              class="form-control form-control-sm p-0"
              v-model.number="parvalue"
            />
          </td>
          <td class="text-center">
            <input
              type="text"
              class="form-control form-control-sm p-0"
              v-model.number="tax"
            />
          </td>
          <td class="text-center">
            <input
              type="text"
              class="form-control form-control-sm p-0"
              v-model.number="cost"
            />
          </td>
          <td class="text-center">
            <input
              type="text"
              class="form-control form-control-sm p-0"
              v-model.number="amount"
            />
          </td>
        </tr>
      </tbody>
    </table>
    <div class="card-body bg-info py-0 text-white">需要退票的航段</div>
    <table class="table table-sm table-striped mb-1">
      <thead>
        <tr>
          <th class="px-1 text-center">出发机场</th>
          <th class="px-1 text-center">到达机场</th>
          <th class="px-1 text-center">出发日期</th>
          <th class="px-1 text-center">航班号</th>
          <th class="px-1 text-center">舱位</th>
          <th class="px-1 text-center d-none d-md-table-cell">出发时间</th>
          <th class="px-1 text-center d-none d-md-table-cell">到达时间</th>
          <th>退？</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(flt, index) in flights" :key="index">
          <td class="text-center">{{ flt.dport }}</td>
          <td class="text-center">{{ flt.aport }}</td>
          <td class="text-center">{{ flt.ddate }}</td>
          <td class="text-center">{{ flt.flightNo }}</td>
          <td class="text-center">{{ flt.subclass }}</td>
          <td class="text-center d-none d-md-table-cell">
            {{ flt.dtime }}
          </td>
          <td class="text-center d-none d-md-table-cell">
            {{ flt.atime }}
          </td>
          <td>
            <input type="checkbox" v-model="flt.selected" />
          </td>
        </tr>
      </tbody>
    </table>
    <div class="card-body py-0">
      <div class="row mb-1">
        <label class="col-form-label col-4 text-end"> 类型 </label>
        <div class="col-8">
          <div class="form-check form-check-inline">
            <input
              class="form-check-input"
              type="radio"
              value="0"
              v-model.number="reasonCode"
            />
            <label class="form-check-label">自愿</label>
          </div>
          <div class="form-check form-check-inline">
            <input
              class="form-check-input"
              type="radio"
              value="1"
              v-model.number="reasonCode"
            />
            <label class="form-check-label">非自愿</label>
          </div>
          <div class="form-check form-check-inline">
            <input
              class="form-check-input"
              type="radio"
              value="4"
              v-model.number="reasonCode"
            />
            <label class="form-check-label">废</label>
          </div>
        </div>
      </div>
      <div class="row mb-1">
        <label class="col-form-label col-4 text-end">
          {{ labelReasonDesc }}
        </label>
        <div class="col-8">
          <input
            type="text"
            class="form-control form-control-sm"
            v-model.trim="reasonDesc"
          />
        </div>
      </div>
      <div class="row mb-1" v-if="reasonCode !== 4">
        <label class="col-form-label col-4 text-end"> 航司退票费率（%） </label>
        <div class="col-8">
          <input
            type="text"
            class="form-control form-control-sm"
            v-model.number="airRefundFeeRate"
          />
          <span class="text-muted small">退票费率，用于计算退票费</span>
        </div>
      </div>
      <div class="row mb-1">
        <label class="col-form-label col-4 text-end">
          {{ labelAirFee }}
        </label>
        <div class="col-4">
          <input
            type="text"
            class="form-control"
            v-model.number="airRefundFee"
          />
        </div>
        <div class="col-4">
          <button
            type="button"
            class="btn btn-secondary me-2"
            @click.stop="queryRefundFee($event.target)"
          >
            查询退票费
          </button>
        </div>
      </div>
      <div class="row mb-1">
        <label class="col-form-label col-4 text-end"> 我司服务费 </label>
        <div class="col-8">
          <input
            type="text"
            class="form-control form-control-sm"
            v-model.number="serviceCharge"
          />
          <template v-if="refundFee > 0">
            <span class="text-muted small"
              >收费标准: {{ refundFee }}元/人/段</span
            >
            <button class="btn btn-sm" @click.stop="autoCalcServiceCharge()">
              自动计算
            </button>
          </template>
        </div>
      </div>
      <div class="row mb-1">
        <label class="col-form-label col-4 text-end"> 实收客户 </label>
        <div class="col-8">
          <input type="text" class="form-control" v-model.number="total" />
          <span class="text-warning"
            >实收客户 等于 我司服务费 加 航司退票费；</span
          >
          <span class="text-muted small"
            >实收客户表示实际收取客户的退票手续费</span
          >
        </div>
      </div>
      <div class="row mb-1">
        <label class="col-form-label col-4 text-end"> 备注 </label>
        <div class="col-8">
          <input
            type="text"
            class="form-control form-control-sm"
            v-model="remark"
          />
        </div>
      </div>
    </div>
    <table class="table table-sm table-striped mb-0">
      <thead>
        <tr>
          <th class="text-center">预退客户</th>
          <th class="text-center">航司预退</th>
          <th class="text-center">利润</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="text-center">{{ psgRefund }}</td>
          <td class="text-center">{{ airRefund }}</td>
          <td class="text-center">
            <template v-if="profit > 0">
              {{ profit }}
            </template>
            <template v-else>
              <span class="text-danger">{{ profit }}</span>
            </template>
          </td>
        </tr>
      </tbody>
    </table>

    <div class="card-footer text-center">
      <button type="button" class="btn btn-primary" @click.stop="ok()">
        创建退票单
      </button>
    </div>
  </div>
</template>

<script>
import $ from "jquery";
import PriceInfo from "@/common/PriceInfo.js";
import { searchServiceTemplateByCustomer } from "@/api/customer.js";
import {
  searchFlightOrderDetail,
  queryOrderRefundFee,
  convertPriceInfo,
} from "@/api/flight.js";
import { createRefundOrderMulti } from "@/api/flight-refund.js";

export default {
  data() {
    return {
      id: 0,
      detail: null,

      customerId: 0,
      psgList: [],
      cost: 0,
      amount: 0,
      parvalue: 0,
      tax: 0,
      orderId: 0,
      orderNo: "",
      airRefundFee: 0,
      serviceCharge: 0,
      remark: "",
      reasonCode: 0,
      reasonDesc: "",
      intlTicket: -1,
      flights: [],

      airRefundFeeRate: 0,
      psgRefund: 0,
      airRefund: 0,
      profit: 0,
      total: 0,

      modalTitle: "申请退票",
      labelReasonDesc: "退票备注",
      labelAirFee: "航司退票费",

      // 退票服务费，单位为：元/人/段
      refundFee: 0,

      myModal: null,
    };
  },
  computed: {},
  watch: {
    airRefundFeeRate: function () {
      this.calc();
    },
    airRefundFee: function () {
      this.calc();
    },
    serviceCharge: function () {
      this.calc();
    },
    reasonCode: function () {
      this.changeOpMode();
    },
    total: function () {
      this.calc2();
    },
    customerId: function () {
      this.getRefundFee();
    },
    refundFee: function () {
      this.calcServiceCharge();
    },
  },
  mounted: function () {
    this.id = parseInt(this.$route.query.id);
    this.searchOrderDetail();
  },
  methods: {
    showErrMsg: function (msg, msgType) {
      this.$store.dispatch("showAlertMsg", {
        errMsg: msg,
        errMsgType: msgType,
      });
    },
    searchOrderDetail: function () {
      searchFlightOrderDetail(this.id, (v) => {
        this.detail = v;
        this.prepareData();
      });
    },
    prepareData: function () {
      this.psgList.splice(0);
      for (const info of this.detail.passengers) {
        this.psgList.push({
          ticketNo: info.ticketNo,
          name: info.name,
          idNo: info.idNo,
          selected: false,
        });
      }

      this.flights = this.detail.flights;

      const psgType = this.detail.passengers[0].psgType;
      let psgPrice = new PriceInfo();
      convertPriceInfo(this.detail.prices, psgType, psgPrice);
      console.log(psgPrice);

      this.amount = psgPrice.amount;
      this.cost = psgPrice.cost;
      this.parvalue = psgPrice.parValue;
      this.tax = psgPrice.tax;

      this.orderNo = this.detail.orderNo;
      this.orderId = this.detail.id;
      this.intlTicket = this.detail.intlTicket;
    },
    ok: function () {
      // 检查是否选择了退票的票号
      let psgCount = 0;
      for (const psg of this.psgList) {
        if (psg.selected) {
          psgCount++;
        }
      }

      if (psgCount === 0) {
        this.showErrMsg("请选择需要退票的票号", "danger");
        return;
      }

      // 检查是否选择了退票航段
      const refundFlights = [];
      let count = 0;
      for (const flt of this.flights) {
        if (flt.selected) {
          count++;
          refundFlights.push(flt);
        }
      }

      if (count === 0) {
        this.showErrMsg("请选择需要退票的航段", "danger");
        return;
      }

      if (
        this.airRefundFee === 0 &&
        this.serviceCharge === 0 &&
        this.remark.length === 0
      ) {
        this.showErrMsg(
          "航司退（废）票费和我司服务费都为0时，请备注说明理由",
          "danger"
        );
        return;
      }

      this.doCreateRefundOrderMulti({
        refundTickets: this.psgList,
        parvalue: this.parvalue,
        tax: this.tax,
        amount: this.amount,
        cost: this.cost,
        airRefundFee: this.airRefundFee,
        serviceCharge: this.serviceCharge,
        orderId: this.orderId,
        orderNo: this.orderNo,
        reasonCode: this.reasonCode,
        reasonDesc: this.reasonDesc,
        remark: this.remark,
        intlTicket: this.intlTicket,
        flights: refundFlights,
      });
    },
    doCreateRefundOrderMulti: function (info) {
      createRefundOrderMulti(JSON.stringify(info), (jsonResult) => {
        if (jsonResult.status !== "OK") {
          this.showErrMsg(jsonResult.errmsg, "danger");
        } else {
          this.showErrMsg("操作成功");
          this.$router.push("/flt/refund/order/" + jsonResult.returnCode);
        }
      });
    },
    reset: function () {
      this.airRefundFeeRate = 0;
      this.airRefundFee = 0;
      this.serviceCharge = 0;
      this.remark = "";
      this.reasonDesc = "";
    },
    modal: function (
      customerId,
      psgList,
      orderId,
      orderNo,
      flights,
      intlTicket,
      amount,
      cost,
      parvalue,
      tax
    ) {
      this.reset();
      this.psgList.splice(0);
      for (const info of psgList) {
        this.psgList.push(info);
      }

      this.customerId = customerId;
      this.amount = amount;
      this.cost = cost;
      this.parvalue = parvalue;
      this.tax = tax;

      this.orderId = orderId;
      this.orderNo = orderNo;
      this.flights.splice(0);
      this.intlTicket = intlTicket;
      for (const flt of flights) {
        // console.log(flt)
        this.flights.push({
          dport: flt.dport,
          dportName: flt.dportName,
          dterm: flt.dterm,
          aport: flt.aport,
          aportName: flt.aportName,
          aterm: flt.aterm,
          ddate: flt.ddate,
          flightNo: flt.flightNo,
          dtime: flt.dtime,
          atime: flt.atime,
          subclass: flt.subclass,
          selected: true,
        });
      }

      this.calc();

      this.showModal();

      this.promise = new Promise((resolve, reject) => {
        this.resolve = resolve;
        this.reject = reject;
      });
      return this.promise;
    },
    calc: function () {
      if (this.airRefundFeeRate !== 0) {
        this.airRefundFee = (this.parvalue * this.airRefundFeeRate) / 100;
      }
      this.psgRefund = this.amount - this.airRefundFee - this.serviceCharge;
      this.airRefund = this.cost - this.airRefundFee;
      this.profit = this.airRefund - this.psgRefund;

      this.total = this.airRefundFee + this.serviceCharge;
    },
    calc2: function () {
      // 实收客户 - 航司服务费 = 我司服务费
      this.serviceCharge = this.total - this.airRefundFee;
    },
    changeOpMode: function () {
      if (this.reasonCode === 0 || this.reasonCode === 1) {
        // 退票
        this.modalTitle = "申请退票";
        this.labelReasonDesc = "退票备注";
        this.labelAirFee = "航司退票费";
      } else if (this.reasonCode === 4) {
        // 废票
        this.modalTitle = "申请废票";
        this.labelReasonDesc = "废票备注";
        this.labelAirFee = "航司废票费";
      }
    },
    getRefundFee: function () {
      searchServiceTemplateByCustomer(this.customerId, (v) => {
        console.log(v);
        if (v !== null && v.flightRefundFee !== undefined) {
          this.refundFee = v.flightRefundFee;
        }
      });
    },
    calcServiceCharge: function () {
      //根据模板设置的服务费来计算
      this.serviceCharge = this.flightCount() * this.refundFee;
      this.calc();
    },
    flightCount: function () {
      let count = 0;
      for (let i = 0; i < this.flights.length; i++) {
        if (this.flights[i].selected) {
          count = count + 1;
        }
      }
      return count;
    },
    autoCalcServiceCharge: function () {
      this.serviceCharge = this.flightCount() * this.refundFee;
      this.calc();
    },
    queryRefundFee: function (btn) {
      $(btn).attr("disabled", true);
      queryOrderRefundFee(
        this.id,
        (v) => {
          if (v.errcode === 0) {
            this.airRefundFee = v.surcharge;
            this.showErrMsg('航司退票费：' + v.surcharge)
          } else {
            this.showErrMsg(v.errmsg, "danger");
          }
        },
        () => $(btn).attr("disabled", false)
      );
    },
  },
};
</script>
